package com.yangqi.ThreadDemo;

/**
 * 使用多线程模拟三个窗口同事售票
 */
public class Thread03 {
    public static void main(String[] args) {
        SellTicket sellTicket01 = new SellTicket();
        SellTicket sellTicket02 = new SellTicket();
        SellTicket sellTicket03 = new SellTicket();
        sellTicket01.start();
        sellTicket02.start();
        sellTicket03.start();
    }

}

class SellTicket extends Thread {
    private static int ticketNum = 10;
    private boolean loop = true;
    Object object = new Object(); //不是同一个对象

    public /*synchronized*/ void sync() {
        synchronized (object){
            if (ticketNum <= 0) {
                System.out.println("售票结束");
                loop = false;
                return;
            }
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println("窗口" + Thread.currentThread().getName() + "售出一张票" + "剩余票数" + (--ticketNum));
        }
    }

    @Override
    public void run() {
        while (loop) {
            sync();
        }
    }

}
